<script setup>
import {inject, reactive, ref} from 'vue'
import {Search} from '@element-plus/icons-vue'
import {useRouter, useRoute} from 'vue-router'
import axios from 'axios'
import {ElMessage} from 'element-plus'

let isLike = ref(false)
const getPath = inject('getPath')
const router = useRouter();
const data = reactive({
  tableData: []
})

//名字
const validatName = (rule, value, callback) => {
  let regx = /^[\u4E00-\u9FA5_0-9_]{3,10}$/
  if (value === '') {
    callback(new Error('仓库名不能为空'))
  } else if (regx.test(value) == false) {
    callback(new Error('请输入正确的仓库名'))
  } else {
    callback()
  }
}
const rules = reactive({
  name: [{validator: validatName, trigger: 'blur'}]
})

//2.新增按钮 新增form默认不显示
const dialogVisible = ref(false)
//3.新增
const addStorage = () => {
  //参数初始化
  init()
  dialogVisible.value = true;
}
//4.保存
const save = (formEl) => {
  if (!formEl) return
  if (ruleForm.id) {
    //修改
    formEl.validate((valid) => {
      if (valid) {
        axios.post(`${getPath}updateStorage`, ruleForm).then(res => {
          console.log(res)
          if (res.data.code == 200) {
            dialogVisible.value = false
            ElMessage({
              message: res.data.msg,
              type: 'success',
            })
            //刷新
            listPage()
            //重置
            init()
          } else {
            ElMessage({
              message: res.data.msg,
              type: 'error',
            })
          }
        })
      } else {
        console.log('error submit!')
      }
    })
  } else {
    //新增
    formEl.validate((valid) => {
      if (valid) {
        axios.post(`${getPath}addStorage`, ruleForm).then(res => {
          dialogVisible.value = false
          if (res.data.code == 200) {
            ElMessage({
              message: res.data.msg,
              type: 'success',
            })
            //刷新
            listPage()
          } else {
            ElMessage({
              message: res.data.msg,
              type: 'error',
            })
          }
        })
      } else {
        console.log('error submit!')
      }
    })
  }
}
//5.创建
const ruleFormRef = ref()
//6.保存form表单的数据
const ruleForm = reactive({
  id: 0,
  name: '',
  remark: ''
})
// 9.删除
const handleDelete = (index) => {
  let id = data.tableData[index].id
  axios({
    url: `${getPath}deleteStorage`,
    method: "post",
    data: {
      id: id
    }
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
      //刷新
      listPage()
    } else {
      ElMessage({
        message: res.data.msg,
        type: 'error',
      })
    }
  })
}
//10.修改
const handleEdit = (index, row) => {
  //修改默认值
  ruleForm.id = row.id
  ruleForm.name = row.name
  ruleForm.remark = row.remark
  //打开修改页面
  dialogVisible.value = true
}
//11初始化参数
const init = () => {
  ruleForm.id = 0
  ruleForm.name = ''
  ruleForm.remark = ''
}
//分页组件
//1.页码
let pageNum = ref(1)
//2.行数
let pageSize = ref(2)
//3.总页数
let total = ref(0)
//4.获取分页列表
const listPage = () => {
  if (isLike.value) {
    query()
  } else {
    axios({
      url: `${getPath}listStoragePage`,
      method: "post",
      data: {
        pageSize: pageSize.value,
        pageNum: pageNum.value,
      }
    }).then(res => {
      if (res.data.code == 200) {
        data.tableData = res.data.data
        total.value = res.data.total
      } else {
        alert("获取数据失败")
      }
    })
  }
}
listPage()
//5.设置行数
const handleSizeChange = (val) => {
  pageNum.value = 1
  pageSize.value = val
  listPage()
}
//6.当前页数
const handleCurrentChange = (val) => {
  pageNum.value = val
  listPage()
}

//模糊查询
const form = reactive({
  name: '',
  pageSize: 2,
  pageNum: 1
})

const reset = () => {
  form.name = ''
  isLike.value = false
  listPage()
}

const query = () => {
  form.pageNum = pageNum.value
  form.pageSize = pageSize.value
  axios.post(`${getPath}likeStoragePage`, form).then(res => {
    if (res.data.code == 200) {
      data.tableData = res.data.data
      total.value = res.data.total
      ElMessage({
        message: res.data.msg,
        type: 'success',
      })
      isLike.value = true
    } else {
      ElMessage({
        message: res.data.msg,
        type: 'error',
      })
    }
  })
}

const tableData = ref()
</script>

<template>
  <div class="warehouse">
    <el-scrollbar>
      <div>
        <el-form ref="ruleFormRef" :model="form" status-icon :rules="rules" label-width="80px">
          <el-input v-model="form.name" placeholder="请输入仓库名" :suffix-icon="Search" style="width: 200px; margin: 5px;"
                    autocomplete="off "></el-input>
          <el-button type="primary" @click="query">查询</el-button>
          <el-button type="success" @click="reset">重置</el-button>
          <el-button type="primary" @click="addStorage()">新增</el-button>

        </el-form>
      </div>
      <el-table :header-cell-style="{background:'#f3f6fd',color:'#555'}" border :data="data.tableData">
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="仓库名" width="140"/>
        <el-table-column prop="remark" label="备注" width="140"/>
        <el-table-column prop="" label="操作" width="200">
          <template #default="scope">
            <el-button
                size="small"
                type="success"
                @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-popconfirm title="确定删除吗?"
                           style="margin-left: 5px"
                           @confirm="handleDelete(scope.$index, scope.row)">
              <template #reference>
                <el-button slot="reference"
                           size="small"
                           type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    <!--分页 -->
    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 新增-->
    <el-dialog
        v-model="dialogVisible"
        title="提示"
        width="500"
    >
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="80px">
        <el-form-item label="仓库名" prop="name">
          <el-col :span="20">
            <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入仓库名"/>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="ruleForm.remark" autocomplete="off" placeholder="请输入备注"/>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>

</style>